package zut.cs.liziflower.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.web.bind.annotation.*;
import zut.cs.liziflower.entity.Consumer;
import zut.cs.liziflower.entity.Result;
import zut.cs.liziflower.entity.login;
import zut.cs.liziflower.mapper.ConsumerMapper;
import zut.cs.liziflower.service.impl.ConsumerServiceImpl;

import javax.annotation.Resource;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author xuwenke
 * @since 2022-05-17
 */
@RestController
@RequestMapping("/api/consumer")
public class ConsumerController {
    @Resource
    private ConsumerServiceImpl consumerImpl;
    @Resource
    private ConsumerMapper conMapper;

    @PostMapping("/login")
    public Result<?> loginIn(@RequestBody login c) {
        //登录
        Consumer consumer = consumerImpl.login(c.getUsername(), c.getPassword());//查找消费者
        if (consumer == null) {
            return Result.error("1001", "登录失败", consumer);
        }
        return Result.success(consumer);
    }

    @PostMapping("/login-up")
    public Result<?> loginUp(@RequestBody Consumer con) {//注册
        Consumer existConsumered = consumerImpl.login(con.getUsername(), con.getPassword());//查找
        QueryWrapper<Consumer> wrapper = new QueryWrapper<>();//条件构造器
        wrapper.eq("username", con.getUsername());
        Consumer usernameExist = conMapper.selectOne(wrapper);
        if (existConsumered == null && usernameExist == null) {//不存在
            con.setMoney((float) 10);
            con.setScore(500);
            conMapper.insert(con);
            return Result.success(null);
        }
        return Result.error("00", "用户名重复", null);
    }

    QueryWrapper<Consumer> wrapper = new QueryWrapper<>();
    boolean flag;

    @PutMapping("/update-info")
    public Result<?> updateInfo(@RequestBody Consumer consumer) {
        //更新  根据 userid 和 consumer.username 的 用户信息
        // 更新用户的 age, sex, phone, password
        flag = consumerImpl.updateInfo(consumer.getUserid(), consumer.getAge(), consumer.getSex(), consumer.getPhone(), consumer.getPassword());
        if (flag == true) {
            return Result.success("更新成功");
        }
        return Result.error("405", "更新失败", null);

    }

    /**
     * 充值
     * @param userid
     * @return
     */
    @PutMapping("/updatemoney")
    public Result<?> updateMoney(@RequestParam("userid") Integer userid,@RequestParam("charge") float charge) {
        QueryWrapper<Consumer> wrapper = new QueryWrapper<>();
        wrapper.eq("userid",userid);
        Consumer consumer = conMapper.selectOne(wrapper);
        consumer.setMoney(consumer.getMoney()+charge);
        conMapper.update(consumer,wrapper);
        return Result.success(consumer);
    }
}
